package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointcut(){}

    @Before("autoFillPointcut()")
    public void before(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 1.获取连接点的签名信息
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 2.获取方法上的注解信息
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        // 3.获取注解中的操作类型
        OperationType operationType = autoFill.value();
        // 4.获取方法的参数信息
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object arg = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long currentUserId = BaseContext.getCurrentId();
        // 5.根据操作类型进行不同的处理
        if(operationType == OperationType.INSERT){
            Method setCreateTime = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
            Method setCreateUser = arg.getClass().getDeclaredMethod("setCreateUser", Long.class);
            Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);
            setCreateTime.invoke(arg, now);
            setCreateUser.invoke(arg, currentUserId);
            setUpdateTime.invoke(arg, now);
            setUpdateUser.invoke(arg, currentUserId);
            log.info("插入操作");
        }else if(operationType == OperationType.UPDATE){
            Method setUpdateTime = arg.getClass().getMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = arg.getClass().getMethod("setUpdateUser", Long.class);
            setUpdateTime.invoke(arg, now);
            setUpdateUser.invoke(arg, currentUserId);
            log.info("更新操作");
        }
    }



}
